package com.pet.shop.utils;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import com.pet.exceptions.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;

/**
 *
 */
public class HttpsClientUtil {

    protected static final Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);

    public static String doPost(String url, Map<String, String> paramMap){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = createHttpsClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> elem : paramMap.entrySet()) {
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        }catch(Exception ex){
            throw new BusinessException(ex.getMessage(), ex);
        }
        logger.info("返回值：{}", result);
        return result;
    }

    private static HttpClient createHttpsClient() throws Exception{
        SSLContext ctx = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            //信任所有
            @Override
            public boolean isTrusted(X509Certificate[] xcs, String string){
                return true;
            }
        }).build();

        return HttpClients.custom().setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();
    }
}
